package com.singerw.handler;

import com.alibaba.fastjson.JSON;
import com.singerw.annotations.ResponseResult;
import com.singerw.pojo.Result;
import com.singerw.pojo.ResultLoginSuccess;
import com.singerw.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @version V1.0
 * @Package com.singerw.handler
 * @auhter 张欣
 * @date 2021/1/4-7:24 PM
 */
@Slf4j
@ControllerAdvice
public class ResponseResultHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return AnnotationUtils.findAnnotation(methodParameter.getAnnotatedElement(), ResponseResult.class) != null;
    }


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ResponseResult responseResult = AnnotationUtils.findAnnotation(methodParameter.getAnnotatedElement(), ResponseResult.class);
        if(o == null){
            o = "success";
        }
        return ResultUtils.success(o);
    }
}